package br.com.tcc.screens;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class LogoCanvas extends Canvas implements Runnable {
	
	Thread thread;
	private Image imgLogo;
	private BufferedImage bufferImage;
	private Graphics2D mGraphics;
	private boolean isRunning;
	
	public LogoCanvas() {
		super();
		
		isRunning = true;
		//this.setIgnoreRepaint(true);
		this.setBounds(0, 0, 640, 192);
		this.setBackground(Color.black);
		
		try {
			imgLogo = ImageIO.read(new File("imagens/logo_form.jpg"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		startAnimation();
	}
	
	public void startAnimation(){
		if (thread == null) {
			thread = new Thread(this);
			thread.start();
		}
	}
	
	public void stopAnimation() {
		if (thread != null) {
			isRunning = false;
			thread = null;
		}
	}
	
	@Override
	public void run() {
		while (isRunning) {
			long startTime = System.currentTimeMillis();

			render();
			paintScreen();
			long timeSinceStart = (startTime - System.currentTimeMillis());
			if (timeSinceStart < (1000 / 25)) {
				try {
					Thread.sleep((1000 / 25) - timeSinceStart);
				} catch (java.lang.InterruptedException e) {
				}
			}
		}
		
	}
	
	public void render() {
		if (bufferImage == null) {
			// bufferImage = createImage(640, 400);
			bufferImage = new BufferedImage(640, 192,
					BufferedImage.TYPE_INT_ARGB);
			if (bufferImage == null) {
				System.out.println("dbImage is null");
				return;
			} else {
				mGraphics = (Graphics2D) bufferImage.createGraphics();
			}
		}

		mGraphics.setPaint(Color.black);
		mGraphics.fillRect(0, 0, 640, 192);

		mGraphics.drawImage(imgLogo, 192, 0, null);

	}
	
	private void paintScreen() throws NullPointerException
	// actively render the buffer image to the screen
	{
		Graphics2D g;
		try {
			g = (Graphics2D) this.getGraphics(); // get the panel's graphic context
			if(g == null){
				//System.out.println("teste 222");
			}
			if ((g != null) && (bufferImage != null))
				g.drawImage(bufferImage, 0, 0, null);
			Toolkit.getDefaultToolkit().sync(); // sync the display on some
												// systems
			g.dispose();
		} catch (Exception e) {
			//System.out.println("Graphics context error: " + e);
		}
	}

}
